﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;

namespace FreeDream.Common.Helper
{
    /// <summary>
    /// 工具类
    /// </summary>
    public static class CommonFun
    {
        public static string GUID => Guid.NewGuid().ToString("N");
        public static bool IsNull(this string s)
        {
            return string.IsNullOrWhiteSpace(s);
        }
        public static bool NotNull(this string s)
        {
            return !string.IsNullOrWhiteSpace(s);
        }
        public static int GetRandom(int minNum, int maxNum)
        {
            var seed = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
            return new Random(seed).Next(minNum, maxNum);
        }
        //public static string ToJson(this object obj)
        //{
        //    return JsonConvert.SerializeObject(obj);
        //}
        public static object GetDefaultVal(string typename)
        {
            return typename switch
            {
                "Boolean" => false,
                "DateTime" => default(DateTime),
                "Date" => default(DateTime),
                "Double" => 0.0,
                "Single" => 0f,
                "Int32" => 0,
                "String" => string.Empty,
                "Decimal" => 0m,
                _ => null,
            };
        }
        public static void CoverNull<T>(T model) where T : class
        {
            if (model == null)
            {
                return;
            }
            var typeFromHandle = typeof(T);
            var properties = typeFromHandle.GetProperties();
            var array = properties;
            for (var i = 0; i < array.Length; i++)
            {
                var propertyInfo = array[i];
                if (propertyInfo.GetValue(model, null) == null)
                {
                    propertyInfo.SetValue(model, GetDefaultVal(propertyInfo.PropertyType.Name), null);
                }
            }
        }
        public static void CoverNull<T>(List<T> models) where T : class
        {
            if (models.Count == 0)
            {
                return;
            }
            foreach (var model in models)
            {
                CoverNull(model);
            }
        }

        #region 文件操作
        public static FileInfo[] GetFiles(string directoryPath)
        {
            if (!IsExistDirectory(directoryPath))
            {
                throw new DirectoryNotFoundException();
            }
            var root = new DirectoryInfo(directoryPath);
            return root.GetFiles();
        }
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
        public static string ReadFile(string Path)
        {
            string s;
            if (!File.Exists(Path))
                s = "不存在相应的目录";
            else
            {
                var f2 = new StreamReader(Path, Encoding.Default);
                s = f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }
            return s;
        }
        public static void FileMove(string OrignFile, string NewFile)
        {
            File.Move(OrignFile, NewFile);
        }
        public static void CreateDir(string dir)
        {
            if (dir.Length == 0) return;
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
        }
        #endregion

        #region IP
        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        public static string GetIP(HttpRequest request)
        {
            if (request == null)
            {
                return "";
            }

            var ip = request.Headers["X-Real-IP"].FirstOrDefault();
            if (ip.IsNull())
            {
                ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
            }
            if (ip.IsNull())
            {
                ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
            }
            if (ip.IsNull() || !IsIP(ip))
            {
                ip = "127.0.0.1";
            }

            return ip;
        }
        #endregion

        #region String  Dictionary

        #region Dictionary Parse To String
        /// <summary>
        /// Dictionary Parse To String
        /// </summary>
        /// <param name="parameters">Dictionary</param>
        /// <returns>String</returns>
        public static string ParseToString(IDictionary<string, string> parameters)
        {
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            StringBuilder query = new StringBuilder("");
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append("=").Append(value).Append("&");
                }
            }
            string content = query.ToString().Substring(0, query.Length - 1);

            return content;
        }
        #endregion

        #region String Parse To Dictionary
        /// <summary>
        /// String Parse To Dictionary
        /// </summary>
        /// <param name="parameter">String</param>
        /// <returns>Dictionary</returns>
        public static Dictionary<string, string> ParseToDictionary(string parameter)
        {
            try
            {
                String[] dataArry = parameter.Split('&');
                Dictionary<string, string> dataDic = new Dictionary<string, string>();
                for (int i = 0; i <= dataArry.Length - 1; i++)
                {
                    String dataParm = dataArry[i];
                    int dIndex = dataParm.IndexOf("=");
                    if (dIndex != -1)
                    {
                        String key = dataParm.Substring(0, dIndex);
                        String value = dataParm.Substring(dIndex + 1, dataParm.Length - dIndex - 1);
                        dataDic.Add(key, value);
                    }
                }

                return dataDic;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #endregion

        #region 1.0 Base64转二进制
        /// <summary>
        /// 传入base64 转为二进制字符串
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static string Base64ImgConveToData(this string values)
        {
            var img = Convert.FromBase64String(values);
            return System.Text.Encoding.Default.GetString(img);
        }
        #endregion

        #region 2.0 json序列化

        public static string ToJson<T>(this T obj)
        {
            return JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
        }
        public static string ToJson2<T>(this T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
        public static string XmlToJson(this XmlNode xml)
        {
            return JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.Indented);
        }
        public static T JsonToObject<T>(this string str)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(str);
            }
            catch
            {
                return default(T);
            }
        }

        public static string GetTimeStamp(this DateTime nowTime)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long unixTime = (long)System.Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
            return unixTime.ToString();
        }
        #endregion

        #region 4.0 获取时间戳
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp13(this System.DateTime time)
        {
            long ts = ConvertDateTimeToInt(time);
            return ts.ToString();
        }

        /// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>long</returns>  
        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t;
        }
        public static long ConvertDateTimeToInt2(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000000;   //除10000调整为13位      
            return t;
        }
        #endregion

        #region 5.0 获取当前主机IPv4地址
        /// <summary>
        /// 获取当前主机IPv4地址
        /// </summary>
        /// <returns></returns>
        public static string GetIpAddress()
        {
            string hostName = Dns.GetHostName();
            IPHostEntry localhost = Dns.GetHostByName(hostName);
            IPAddress localaddr = localhost.AddressList[0];
            return localaddr.ToString();
        }

        #endregion

        #region 6.0 Base64名字解密
        public static string Base64Tostring(this string str)
        {
            byte[] bytes = Convert.FromBase64String(str);
            try
            {
                string retStr = Encoding.UTF8.GetString(bytes);
                return retStr;
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 7.Base64编码
        public static string EncodeBase64(string code_type, string code)
        {
            string encode = "";
            byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code); //将一组字符编码为一个字节序列. 
            try
            {
                encode = Convert.ToBase64String(bytes); //将8位无符号整数数组的子集转换为其等效的,以64为基的数字编码的字符串形式. 
            }
            catch
            {
                encode = code;
            }
            return encode;
        }
        #endregion

        #region 8.0 日期转换
        /// <summary>
        /// Excel 日期格式转换
        /// </summary>
        /// <param name="exdate"></param>
        /// <returns></returns>
        public static DateTime TransExcelNumData(this string exdate)
        {
            DateTime alreadytime = DateTime.Now;
            if (DateTime.TryParse(exdate, out alreadytime))
            {
                return alreadytime;
            }
            else
            {
                string strDate = DateTime.FromOADate(Convert.ToInt32(exdate)).ToString("d");
                strDate = DateTime.Parse(strDate).ToString("yyyy-MM-dd");
                return Convert.ToDateTime(strDate);
            }
        }
        #endregion

        #region 9.0 时间差
        public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            string dateDiff = null;
            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);

            TimeSpan ts = ts1.Subtract(ts2).Duration();

            //dateDiff = ts.Days + "天" + ts.Hours + "小时" + ts.Minutes + "分钟" + ts.Seconds + "秒";
            dateDiff = ts.Days + " day " + ts.Hours + " hour " + ts.Minutes + " minutes ";//+ ts.Seconds+ " seconds ";
            return dateDiff;
        }
        #endregion

        #region 10.0 相差天数
        public static double DateDiffDay(DateTime dt1, DateTime dt2)
        {

            TimeSpan ts = dt2.Subtract(dt1);
            Console.WriteLine("相差天数：{0}", ts.TotalDays);
            return ts.TotalDays;
        }
        #endregion

        #region 11.0 密码强校验
        /// <summary>
        /// 必须满足 字符数字 并8位数以上
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static bool VailPassword(this string pwd)
        {
            return Regex.IsMatch(pwd, @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}");
        }
        #endregion

        #region 12.0 读取自定义配置Json文件
        /// <summary>
        /// 自定义json读取模型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fullurl">文件全路径</param>
        /// <returns></returns>
        public static T ReadConfigJson<T>(string fullurl)
        {
            using (StreamReader reader = new StreamReader(fullurl, Encoding.Default))
            {
                StringBuilder sb = new StringBuilder();
                while (!reader.EndOfStream)
                {
                    sb.AppendLine(reader.ReadLine());
                }
                reader.Close();
                if (!string.IsNullOrWhiteSpace(sb.ToString()))
                {
                    // return sb.ToString().JsonToObject<T>();

                    return JsonConvert.DeserializeObject<T>(sb.ToString());
                }
            }
            return default;
        }
        #endregion

        #region 13.0 字母转换为数字

        public static int AlgNumConvNum(this string str)
        {
            byte[] array = new byte[1];   //定义一组数组array
            array = System.Text.Encoding.ASCII.GetBytes(str); //string转换的字母
            int asciicode = (short)(array[0]);
            return asciicode - 64;
        }
        #endregion

        #region 14.0 统一任务号生成
        /// <summary>
        /// TransactionID – { MachineID + epoch(datetime) + GUID }
        /// </summary>
        /// <param name="machineId"></param>
        /// <returns></returns>
        public static string CreateTransactionId(this string machineId)
        {
            Thread.Sleep(100);
            return $"{machineId}-{ConvertDateTimeToInt2(DateTime.Now)}-{Guid.NewGuid()}";
        }
        #endregion

        #region 15.0 身份证相关
        #region 1.0 是否身份证号码格式 s + bool IsIDCard(this string InputStr)
        /// <summary>
        /// 是否身份证号码格式
        /// </summary>
        /// <param name="InputStr"></param>
        /// <returns></returns>
        public static bool IsIDCard(this string InputStr)
        {
            if (InputStr.Length == 18)
            {
                bool check = CheckIDCard18(InputStr);
                return check;
            }
            else if (InputStr.Length == 15)
            {
                bool check = CheckIDCard15(InputStr);
                return check;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 2.0 身份证长度判断 s + bool CheckIDCard18(string Id)
        private static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }

        private static bool CheckIDCard15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }
        #endregion

        #region 3.0 根据身份证推算年纪 s +  int GetAgeFromIdCard(this string idCard)
        /// <summary>
        /// 根据身份证推算年纪
        /// </summary>
        /// <param name="idCard">idcard</param>
        /// <returns></returns>
        public static int GetAgeFromIdCard(this string idCard)
        {
            var age = -1;
            if (idCard.IsIDCard())
            {
                if (idCard.Length == 18)
                {
                    string birth = idCard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
                    age = DateTime.Now.Year - Convert.ToDateTime(birth).Year;
                }
                if (idCard.Length == 15)
                {
                    string birth = idCard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
                    age = DateTime.Now.Year - Convert.ToDateTime(birth).Year;
                }
            }
            return age;
        }
        #endregion

        #region 4.0 通过身份证计算性别
        /// <summary>
        /// 计算性别
        /// </summary>
        /// <param name="identityCard"></param>
        /// <returns></returns>
        public static string GetSexByIdCard(this string identityCard)
        {
            string strSex = string.Empty;
            string returnSex = string.Empty;
            if (identityCard.IsIDCard())
            {
                if (identityCard.Length == 18)//处理18位的身份证号码从号码中得到生日和性别代码
                {
                    strSex = identityCard.Substring(14, 3);
                }
                if (identityCard.Length == 15)
                {
                    strSex = identityCard.Substring(12, 3);
                }
                if (int.Parse(strSex) % 2 == 0)//性别代码为偶数是女性奇数为男性
                {
                    returnSex = "女";
                }
                else
                {
                    returnSex = "男";
                }
            }
            return string.IsNullOrEmpty(returnSex) ? "男" : returnSex;
        }
        #endregion

        #region 5.0根据身份证号码获取生日
        public static string GetBirthDayFormIdCard(this string idCard)
        {
            string year = idCard.Substring(6, 4);
            string month = idCard.Substring(10, 2);
            string date = idCard.Substring(12, 2);
            string result = year + "-" + month + "-" + date;
            return result;
        }
        #endregion
        #endregion

        #region 16.0 hex
        public static string ToHexString(this byte[] bytes)
        {
            var hex = new StringBuilder(bytes.Length * 2);
            foreach (var b in bytes)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            return hex.ToString();
        }
        #endregion

        #region 17.0 TaskID Created

        public static string CreateIscsTaskId()
        {
            return Guid.NewGuid() + "-" + DateTime.Now.GetTimeStamp13();
        }
        public static string GetRandomStr(int length)
        {
            //32位字符串
            return Guid.NewGuid().ToString("N")[..(length > 32 ? 32 : length)];
        }
        #endregion 

        #region Md5
        #region 4 Md5
        /// <summary>
        /// 带补全
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5(this string str)
        {
            try
            {
                var md5 = MD5.Create();
                var bytValue = Encoding.UTF8.GetBytes(str);
                var bytHash = md5.ComputeHash(bytValue);
                md5.Clear();
                string sTemp = "";
                foreach (var t in bytHash)
                {
                    sTemp += t.ToString("X").PadLeft(2, '0');
                }
                str = sTemp.ToLower();
            }
            catch (Exception)
            {
                //Console.WriteLine(e.Message);
            }

            return str;
        }
        #endregion

        #region 5.MD5加密
        /// <summary>
        /// x2 不带补全
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public static string GenerateMd5(this string txt)
        {
            using (MD5 mi = MD5.Create())
            {
                byte[] buffer = Encoding.Default.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }
        #endregion
        #endregion

        #region 计算指定日期的星期值

        /// <summary>
        /// 计算指定日期的星期值。星期日为0，其他为对应的星期值
        /// 默认返回：int类型的星期值
        /// </summary>
        /// <param name="rq"> A System.DateTime</param>
        public static int CaculateWeekDay(DateTime rq)
        {
            int y = rq.Year;
            int m = rq.Month;
            int d = rq.Day;
            if (m == 1 || m == 2)
            {
                m += 12;
                y--;
            }
            int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400 + 1) % 7;
            if (week == 0) return 7;
            else return week;
        }

        #endregion
    }
}
